import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, SafeAreaView, TextInput, FlatList, TouchableOpacity, Alert, Image, ActivityIndicator, RefreshControl, Modal, Dimensions } from 'react-native';
import Header from '../../../components/Header';
import { querySrn, confirmSrn } from './api';
import { SrnRecord, SrnBodyItem } from './types';
import { Toast } from '@ant-design/react-native';
import { styles } from './styles';

interface SrnHeaderProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const SrnHeader: React.FC<SrnHeaderProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [srnList, setSrnList] = useState<SrnRecord[]>([]);
    const [keyword, setKeyword] = useState('');
    const [loading, setLoading] = useState(false);

    // 分页相关状态
    const [current, setCurrent] = useState(1);
    const [size] = useState(10);
    const [hasMore, setHasMore] = useState(true);
    const [loadingMore, setLoadingMore] = useState(false);
    const [refreshing, setRefreshing] = useState(false);

    // 收起展开状态 - 改为管理每个物料项目的展开状态
    const [expandedItems, setExpandedItems] = useState<{ [key: string]: boolean }>({});

    // 选择状态
    const [selectedItems, setSelectedItems] = useState<{ [key: string]: string[] }>({});
    const [selectAllMap, setSelectAllMap] = useState<{ [key: string]: boolean }>({});

    // 图片预览状态
    const [imageModalVisible, setImageModalVisible] = useState(false);
    const [selectedImage, setSelectedImage] = useState<string>('');

    const fetchAsnData = async (searchKeyword?: string, isLoadMore: boolean = false) => {
        if (isLoadMore) {
            setLoadingMore(true);
        } else {
            setLoading(true);
            setCurrent(1);
            setHasMore(true);
        }

        try {
            const params = {
                current: isLoadMore ? current + 1 : 1,
                size,
                type: "WAIT_CONFIRM",
                ...(searchKeyword && { keyword: searchKeyword })
            };

            console.log('开始调用 querySrn 接口...');
            const response = await querySrn(params);
            console.log('querySrn 接口调用成功');

            if (response.code === 200) {
                const newRecords = response.data.records || [];
                const total = response.data.total || 0;

                if (isLoadMore) {
                    setSrnList(prev => [...prev, ...newRecords]);
                    setCurrent(prev => prev + 1);
                } else {
                    setSrnList(newRecords);
                    setCurrent(1);
                }

                // 判断是否还有更多数据
                const totalLoaded = isLoadMore ? srnList.length + newRecords.length : newRecords.length;
                setHasMore(totalLoaded < total);
            }
        } catch (error) {
            console.error('queryAsn 接口调用失败:', error);
            if (!isLoadMore) {
                setSrnList([]);
            }
        } finally {
            if (isLoadMore) {
                setLoadingMore(false);
            } else {
                setLoading(false);
            }
        }
    };

    useEffect(() => {
        fetchAsnData();
    }, []);

    // 滑动到底部加载更多
    const handleLoadMore = () => {
        if (hasMore && !loadingMore && !loading) {
            fetchAsnData(keyword, true);
        }
    };

    // 下拉刷新
    const handleRefresh = async () => {
        setRefreshing(true);
        await fetchAsnData(keyword, false);
        setRefreshing(false);
    };

    // 防抖搜索函数
    const debouncedSearch = useCallback(
        (() => {
            let timeoutId: NodeJS.Timeout;
            return (searchKeyword: string) => {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    fetchAsnData(searchKeyword, false);
                }, 500); // 500ms 延迟
            };
        })(),
        []
    );

    const handleSearch = () => {
        fetchAsnData(keyword, false);
    };

    const handleKeywordChange = (text: string) => {
        setKeyword(text);
        if (text.trim() === '') {
            // 如果搜索框为空，立即搜索所有数据
            fetchAsnData('', false);
        } else {
            // 否则使用防抖搜索
            debouncedSearch(text);
        }
    };

    const handleConfirmArrival = async (item: SrnRecord) => {
        const selectedBodyIds = selectedItems[item.id] || [];

        if (selectedBodyIds.length === 0) {
            Toast.info('请先选择要确认出货的物料');
            return;
        }

        Alert.alert(
            '确认出货',
            `确定要确认出货 ${selectedBodyIds.length} 个物料吗？`,
            [
                {
                    text: '取消',
                    style: 'cancel'
                },
                {
                    text: '确认',
                    onPress: async () => {
                        try {
                            setLoading(true);
                            const response = await confirmSrn(selectedBodyIds);

                            if (response.code === 200) {
                                Toast.success('确认出货成功');
                                // 清空选择状态
                                setSelectedItems(prev => ({
                                    ...prev,
                                    [item.id]: []
                                }));
                                setSelectAllMap(prev => ({
                                    ...prev,
                                    [item.id]: false
                                }));
                                // 刷新数据
                                await fetchAsnData(keyword, false);
                            } else {
                                Toast.fail(response.msg || '确认出货失败');
                            }
                        } catch (error) {
                            console.error('确认出货失败:', error);
                            Toast.fail('确认出货失败，请重试');
                        } finally {
                            setLoading(false);
                        }
                    }
                }
            ]
        );
    };

    // 切换展开收起状态 - 改为管理每个物料项目
    const toggleExpand = (bodyId: string) => {
        setExpandedItems(prev => ({
            ...prev,
            [bodyId]: !prev[bodyId]
        }));
    };

    // 切换单个物料选择状态
    const toggleItemSelection = (asnId: string, bodyId: string) => {
        setSelectedItems(prev => {
            const currentSelected = prev[asnId] || [];
            const newSelected = currentSelected.includes(bodyId)
                ? currentSelected.filter(id => id !== bodyId)
                : [...currentSelected, bodyId];

            return {
                ...prev,
                [asnId]: newSelected
            };
        });
    };

    // 全选/取消全选
    const toggleSelectAll = (asnId: string) => {
        const currentAsn = srnList.find(item => item.id === asnId);
        if (!currentAsn) return;

        const isAllSelected = selectAllMap[asnId];
        const allBodyIds = currentAsn.body_list.map(item => item.id);

        if (isAllSelected) {
            // 取消全选
            setSelectedItems(prev => ({
                ...prev,
                [asnId]: []
            }));
            setSelectAllMap(prev => ({
                ...prev,
                [asnId]: false
            }));
        } else {
            // 全选
            setSelectedItems(prev => ({
                ...prev,
                [asnId]: allBodyIds
            }));
            setSelectAllMap(prev => ({
                ...prev,
                [asnId]: true
            }));
        }
    };

    const renderAsnItem = ({ item }: { item: SrnRecord }) => {
        const currentSelected = selectedItems[item.id] || [];
        const isAllSelected = selectAllMap[item.id];

        return (
            <View style={styles.card}>
                <View style={styles.cardHeader}>
                    <View style={styles.headerRow}>
                        <Text style={styles.label}>单号</Text>
                        <Text style={styles.value}>{item.srn_num}</Text>
                    </View>
                    <View style={styles.headerRow}>
                        <Text style={styles.label}>业务单号</Text>
                        <Text style={styles.value}>{item.odd_num || '-'}</Text>
                    </View>
                </View>

                {/* 渲染 body_list 中的物料信息 */}
                {item.body_list && item.body_list.map((bodyItem, index) => {
                    const isSelected = currentSelected.includes(bodyItem.id);
                    const isExpanded = expandedItems[bodyItem.id];

                    return (
                        <View key={bodyItem.id} style={styles.bodyItem}>
                            {/* 头部信息：图片、物料编码和数量 */}
                            <View style={styles.bodyItemHeader}>
                                <View style={styles.bodyItemLeft}>
                                    <TouchableOpacity
                                        onPress={() => {
                                            setSelectedImage(bodyItem.product_link ? String(bodyItem.product_link) : '');
                                            setImageModalVisible(true);
                                        }}
                                    >
                                        <Image
                                            source={bodyItem.product_link ? { uri: bodyItem.product_link } : require('../../../assets/zwtp.png')}
                                            style={styles.productImage}
                                            resizeMode="contain"
                                        />
                                    </TouchableOpacity>
                                    <View style={styles.bodyItemInfo}>
                                        <Text style={styles.bodyItemLabel}>物料编码</Text>
                                        <Text style={styles.bodyItemValue}>{bodyItem.product_encode}</Text>
                                        <Text style={styles.bodyItemLabel}>数量</Text>
                                        <Text style={styles.bodyItemValue}>{bodyItem.quantity}</Text>
                                    </View>
                                </View>
                                <View style={styles.bodyItemRight}>
                                    <TouchableOpacity
                                        style={[
                                            styles.checkbox,
                                            isSelected && styles.checkboxSelected
                                        ]}
                                        onPress={() => toggleItemSelection(item.id, bodyItem.id)}
                                    >
                                        {isSelected && (
                                            <Image
                                                source={require('../../../assets/duihao.png')}
                                                style={styles.checkboxIcon}
                                            />
                                        )}
                                    </TouchableOpacity>
                                </View>
                            </View>

                            {/* 展开的详细信息 */}
                            {isExpanded && (
                                <View style={styles.expandedDetails}>
                                    <View style={styles.detailsContent}>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>型号</Text>
                                            <Text style={styles.detailValue}>: {bodyItem.product_model}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>物料规格</Text>
                                            <Text style={styles.detailValue}>: {bodyItem.product_specs}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>计划时间</Text>
                                            <Text style={styles.detailValue}>: {bodyItem.send_time}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>客户</Text>
                                            <Text style={styles.detailValue}>: {bodyItem.customer_name}</Text>
                                        </View>
                                    </View>
                                </View>
                            )}

                            {/* 每个物料项目都有自己的展开收起按钮 */}
                            <TouchableOpacity
                                style={styles.expandButton}
                                onPress={() => toggleExpand(bodyItem.id)}
                            >
                                <Text style={styles.expandButtonText}>
                                    {isExpanded ? '收起' : '展开'}
                                </Text>
                            </TouchableOpacity>
                        </View>
                    );
                })}

                {/* 全选和确认出货按钮 */}
                <View style={styles.bottomActions}>
                    <TouchableOpacity
                        style={styles.selectAllContainer}
                        onPress={() => toggleSelectAll(item.id)}
                    >
                        <View style={[
                            styles.checkbox,
                            isAllSelected && styles.checkboxSelected
                        ]}>
                            {isAllSelected && (
                                <Image
                                    source={require('../../../assets/duihao.png')}
                                    style={styles.checkboxIcon}
                                />
                            )}
                        </View>
                        <Text style={styles.selectAllText}>全选</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={[
                            styles.confirmButton,
                            currentSelected.length === 0 && styles.confirmButtonDisabled
                        ]}
                        onPress={() => handleConfirmArrival(item)}
                        disabled={currentSelected.length === 0}
                    >
                        <Text style={[
                            styles.confirmButtonText,
                            currentSelected.length === 0 && styles.confirmButtonTextDisabled
                        ]}>
                            确认出货 {currentSelected.length > 0 ? `(${currentSelected.length})` : ''}
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        );
    };

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="待出货"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            <View style={styles.content}>
                <View style={styles.searchContainer}>
                    <TextInput
                        style={styles.searchInput}
                        placeholder="请输入出库单号或销售单号搜索"
                        placeholderTextColor="#999"
                        value={keyword}
                        onChangeText={handleKeywordChange}
                        returnKeyType="search"
                    />
                </View>

                {loading ? (
                    <View style={styles.loadingContainer}>
                        <ActivityIndicator size="large" color="#007AFF" />
                        <Text style={styles.loadingText}>搜索中...</Text>
                    </View>
                ) : (
                    <FlatList
                        data={srnList}
                        renderItem={renderAsnItem}
                        keyExtractor={(item) => item.id}
                        contentContainerStyle={styles.listContainer}
                        showsVerticalScrollIndicator={false}
                        onEndReached={handleLoadMore}
                        onEndReachedThreshold={0.1}
                        refreshControl={
                            <RefreshControl
                                refreshing={refreshing}
                                onRefresh={handleRefresh}
                                colors={['#007AFF']}
                                tintColor="#007AFF"
                            />
                        }
                        ListEmptyComponent={
                            srnList.length === 0 ? (
                                <View style={styles.emptyContainer}>
                                    <Image
                                        source={require('../../../assets/zwsj.png')}
                                        style={styles.emptyImage}
                                        resizeMode="contain"
                                    />
                                    <Text style={styles.emptyText}>暂无数据</Text>
                                </View>
                            ) : null
                        }
                        ListFooterComponent={
                            loadingMore ? (
                                <View style={styles.loadingMoreContainer}>
                                    <ActivityIndicator size="small" color="#007AFF" />
                                    <Text style={styles.loadingMoreText}>加载更多...</Text>
                                </View>
                            ) : null
                        }
                    />
                )}
            </View>

            {/* 图片全屏显示模态框 */}
            <Modal visible={imageModalVisible} transparent={true} animationType="fade">
                <View style={styles.imageModalContainer}>
                    <TouchableOpacity
                        style={styles.imageModalOverlay}
                        onPress={() => setImageModalVisible(false)}
                    >
                        <Image
                            source={selectedImage ? { uri: selectedImage } : require('../../../assets/zwtp.png')}
                            style={styles.fullScreenImage}
                            resizeMode="contain"
                        />
                    </TouchableOpacity>
                </View>
            </Modal>
        </SafeAreaView>
    );
};

export default SrnHeader; 